#include <stdio.h>
#include <mysql.h>
//#include "./test.h"

void finish_with_error(MYSQL *conn) {
    fprintf(stderr, "%s\n", mysql_error(conn));
    mysql_close(conn);
    exit(1);
}

void testInsert(MYSQL *pConn) {


    if (mysql_query(pConn, "CREATE TABLE cars("
                           "id INT PRIMARY KEY AUTO_INCREMENT,"
                           "name VARCHAR(255),"
                           "price INT"
                           ")")) {

        finish_with_error(pConn);
    }

    if (mysql_query(pConn, "INSERT INTO cars VALUES (1,'Audi',52642)")) {
        finish_with_error(pConn);
    }

    if (mysql_query(pConn, "INSERT INTO cars VALUES (2,'Mercedes',57127)")) {
        finish_with_error(pConn);
    }

    if (mysql_query(pConn, "INSERT INTO cars VALUES (3,'Skoda',9000)")) {
        finish_with_error(pConn);
    }
}

//测试检索
void testSelect(MYSQL *conn) {

    if (mysql_query(conn, "SELECT * FROM cars")) {
        finish_with_error(conn);
    }
    MYSQL_RES *result = mysql_store_result(conn);
    if (NULL == result) {
        finish_with_error(conn);
    }

    int num = mysql_num_fields(result);
    MYSQL_ROW row;
    MYSQL_FIELD *field;
    while (field = mysql_fetch_field(result)) {
        printf("%s ", field->name);
    }
    printf("\n");
    while ((row = mysql_fetch_row(result))) {
        for (int i = 0; i < num; ++i) {

            /*if (i == 0) {

            }*/
            printf("%s ", row[i] ? row[i] : "NULL");
        }

        printf("\n");
    }

    mysql_free_result(result);
}

int main() {
    printf("Hello, World!\n");
//    sayHello();

    MYSQL *pConn = mysql_init(NULL);
    MYSQL *ret = mysql_real_connect(pConn, "192.168.71.128", "root", "root", "testdb", 3306, NULL, 0);
    if (ret == NULL) {
        fprintf(stderr, "%s\n", mysql_error(pConn));
        mysql_close(pConn);
        exit(1);
    } else {
        printf("数据库链接成功！\n");
    }
    //如果存在先删除数据库
//    if (mysql_query(pConn, "DROP TABLE IF EXISTS testdb")) {
//        finish_with_error(pConn);
//    }

    //创建数据库
//    if (mysql_query(pConn, "CREATE DATABASE testdb")) {
//
//        fprintf(stderr, "%s\n", mysql_error(pConn));
//        mysql_close(pConn);
//        exit(1);
//    }

    //创建数据表
    /* if (mysql_query(pConn, "DROP TABLE IF EXISTS cars")) {

         finish_with_error(pConn);
     }

     testInsert(pConn);*/

//    testSelect(pConn);


    if (mysql_query(pConn, "INSERT INTO cars (name,price) VALUES ('sanling',5000)")) {
        finish_with_error(pConn);
    }


    mysql_close(pConn);
    printf("end!\n");
    return 0;
}
